from datetime import datetime
from app import db


class Menu(db.Model):
    """菜单模型"""
    __tablename__ = 'menu'
    
    id = db.Column(db.Integer, primary_key=True)
    parent_id = db.Column(db.Integer, db.ForeignKey('menu.id'), nullable=True, comment='父菜单ID')
    name = db.Column(db.String(100), nullable=False, comment='菜单名称')
    icon = db.Column(db.String(100), comment='图标')
    order_num = db.Column(db.Integer, default=0, comment='排序')
    path = db.Column(db.String(200), comment='路由地址')
    visible = db.Column(db.Boolean, default=True, comment='是否可见')
    status = db.Column(db.Boolean, default=True, comment='状态(True=启用,False=禁用)')
    create_time = db.Column(db.DateTime, default=datetime.utcnow, comment='创建时间')
    update_time = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, comment='更新时间')
    
    # 自引用关系
    parent = db.relationship('Menu', remote_side=[id], backref='children')
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'parent_id': self.parent_id,
            'parent_name': self.parent.name if self.parent else None,
            'name': self.name,
            'icon': self.icon,
            'order_num': self.order_num,
            'path': self.path,
            'visible': self.visible,
            'status': self.status,
            'create_time': self.create_time.strftime('%Y-%m-%d %H:%M:%S') if self.create_time else None,
            'update_time': self.update_time.strftime('%Y-%m-%d %H:%M:%S') if self.update_time else None
        }
    
    def to_tree_dict(self):
        """转换为树形字典"""
        return {
            'id': self.id,
            'name': self.name,
            'icon': self.icon,
            'path': self.path,
            'parent_id': self.parent_id,
            'order_num': self.order_num,
            'visible': self.visible,
            'children': [child.to_tree_dict() for child in sorted(self.children, key=lambda x: x.order_num) if child.status]
        }
    
    def to_tree_dict_for_permission(self):
        """权限配置专用：转换为树形字典（包含所有启用的子菜单和权限信息）"""
        # 获取所有启用的子菜单
        enabled_children = [
            child for child in sorted(self.children, key=lambda x: x.order_num) 
            if child.status
        ]
        
        # 模拟菜单权限信息（这里可以根据实际需求扩展）
        menu_permission = [
            {'id': f"{self.id}_view", 'name': '查看', 'checked': False},
            {'id': f"{self.id}_add", 'name': '新增', 'checked': False},
            {'id': f"{self.id}_edit", 'name': '修改', 'checked': False},
            {'id': f"{self.id}_delete", 'name': '删除', 'checked': False}
        ]
        
        return {
            'id': self.id,
            'name': self.name,
            'icon': self.icon,
            'path': self.path,
            'parent_id': self.parent_id,
            'order_num': self.order_num,
            'visible': self.visible,
            'parent': self.parent_id,  # 兼容前端的parent字段
            'menuPermission': menu_permission,  # 菜单权限信息
            'children': [child.to_tree_dict_for_permission() for child in enabled_children]
        }
    
    def to_tree_dict_with_permission(self, allowed_menu_ids):
        """根据权限转换为树形字典"""
        # 过滤有权限的子菜单
        allowed_children = [
            child for child in sorted(self.children, key=lambda x: x.order_num) 
            if child.status and child.id in allowed_menu_ids
        ]
        
        return {
            'id': self.id,
            'name': self.name,
            'icon': self.icon,
            'path': self.path,
            'parent_id': self.parent_id,
            'order_num': self.order_num,
            'visible': self.visible,
            'children': [child.to_tree_dict_with_permission(allowed_menu_ids) for child in allowed_children]
        } 